package com.zhoujing.myrabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 周敬
 * @version 1.0
 * @createTime 2022/7/19-22:40-星期二
 * <p>
 * 延时队列
 */
@Configuration
public class DelayedQueueConfig {

    /**
     * 队列名称
     */
    public static final String DELAYED_QUEUE_NAME = "delayed.queue";
    /**
     * 交换机名称
     */
    public static final String DELAYED_EXCHANGE_NAME = "delayed.exchange";
    /**
     * 路由Key
     */
    public static final String DELAYED_ROUTING_KEY = "delayed.routingKey";

    /**
     * 声明延时队列
     *
     * @return
     */
    @Bean
    public Queue delayedQueue() {
        return QueueBuilder.durable(DELAYED_QUEUE_NAME).build();
    }

    /**
     * 声明交换机
     * 因为API没有提供“x-delayed-message”类型所以返回为类型为自定义交换机
     *
     * @return
     */
    @Bean
    public CustomExchange delayedExchange() {
        // 消息确实是延迟了,但是怎么传播到队列呢,是要扇出呢还是直连呢,所以这里还得设置类型
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-delayed-type", "direct");
        /*
         * 1、交换机名称
         * 2、交换机类型
         * 3、是否需要持久化
         * 4、是否需要自动删除
         * 5、其他参数
         * */
        return new CustomExchange(DELAYED_EXCHANGE_NAME, "x-delayed-message", true, false, arguments);
    }


    /**
     * 延时队列与延时交换机进行绑定
     * @param delayedQueue 延时队列
     * @param delayedExchange 延时交换机
     * @return
     */
    @Bean
    public Binding delayedQueueBinDingExchange(@Qualifier("delayedQueue") Queue delayedQueue, @Qualifier("delayedExchange") CustomExchange delayedExchange) {
        // noargs:自定义交换机需要构建
        return BindingBuilder.bind(delayedQueue).to(delayedExchange).with(DELAYED_ROUTING_KEY).noargs();
    }
}
